const express = require('express');
const router = express.Router();
const Canvas = require('../models/Canvas');
const auth = require('../middleware/auth');
const crypto = require('crypto');

// 获取画布列表
router.get('/list', auth, async(req, res) => {
    try {
        // 获取用户创建的和协作的画布
        const canvases = await Canvas.find({
                $or: [
                    { owner: req.user.userId },
                    { collaborators: req.user.userId }
                ]
            })
            .populate('owner', 'username') // 添加所有者信息
            .sort({ updatedAt: -1 });

        if (!canvases) {
            return res.status(404).json({
                success: false,
                msg: '未找到画布',
                data: []
            });
        }

        // 为每个画布添加所有权信息
        const canvasesWithOwnership = canvases.map(canvas => {
            const canvasObj = canvas.toObject();
            canvasObj.isOwner = canvas.owner._id.toString() === req.user.userId;
            return canvasObj;
        });

        res.json({
            success: true,
            msg: '获取画布列表成功',
            data: canvasesWithOwnership
        });
    } catch (error) {
        console.error('获取画布列表失败:', error);
        res.status(500).json({
            success: false,
            msg: '获取画布列表失败',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});

// 创建新画布
router.post('/canvas', auth, async(req, res) => {
    try {
        const { title, img } = req.body;
        const canvas = new Canvas({
            title,
            img,
            owner: req.user.userId
        });
        await canvas.save();
        res.status(201).json({
            code: 200,
            msg: '创建画布成功',
            data: canvas._id

        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: '创建画布失败',
            data: null,
            error: error.message
        });
    }
});

// 删除画布
router.delete('/canvas/:id', auth, async(req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.userId;

        // 验证画布ID格式
        if (!require('mongoose').Types.ObjectId.isValid(id)) {
            return res.status(400).json({
                success: false,
                msg: '无效的画布ID格式'
            });
        }

        // 查找画布并验证权限
        const canvas = await Canvas.findOne({
            _id: id,
            $or: [
                { owner: userId },
                { collaborators: userId }
            ]
        });

        if (!canvas) {
            return res.status(404).json({
                success: false,
                msg: '画布不存在或您没有权限'
            });
        }

        // 如果是协作者，从协作者列表中移除
        if (canvas.owner.toString() !== userId.toString()) {
            canvas.collaborators = canvas.collaborators.filter(
                collaboratorId => collaboratorId.toString() !== userId.toString()
            );
            await canvas.save();
            return res.json({
                success: true,
                msg: '已退出协作'
            });
        }

        // 如果是所有者，删除整个画布
        await Canvas.deleteOne({ _id: id });
        res.json({
            success: true,
            msg: '画布已删除'
        });
    } catch (error) {
        console.error('删除画布失败:', error);
        res.status(500).json({
            success: false,
            msg: '删除画布失败',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});

// 更新画布
router.put('/canvas', auth, async(req, res) => {
    try {
        const { canvasId, title, img, zoom } = req.body;
        const updateData = { title };
        if (img) {
            updateData.img = img;
        }
        if (zoom !== undefined) {
            updateData.zoom = zoom;
        }
        const canvas = await Canvas.findOneAndUpdate({
                _id: canvasId,
                $or: [
                    { owner: req.user.userId },
                    { collaborators: req.user.userId }
                ]
            },
            updateData, { new: true }
        );
        if (!canvas) {
            return res.status(404).json({
                code: 404,
                msg: '画布不存在',
                data: null
            });
        }
        res.json({
            code: 200,
            msg: '更新成功',
            data: canvas
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: '更新画布失败',
            data: null,
            error: error.message
        });
    }
});

// 获取特定画布
router.get('/canvas/:id', auth, async(req, res) => {
    try {
        const canvas = await Canvas.findOne({
            _id: req.params.id,
            owner: req.user.userId
        });
        if (!canvas) {
            return res.status(404).json({
                code: 404,
                msg: '画布不存在',
                data: null
            });
        }
        res.json({
            code: 200,
            msg: '获取画布成功',
            data: canvas
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: '获取画布失败',
            data: null,
            error: error.message
        });
    }
});

// 获取画布快照
router.get('/canvas-snapshots/:canvasId', auth, async(req, res) => {
    try {
        console.log('正在获取画布快照:', req.params.canvasId);
        console.log('当前用户ID:', req.user.userId);

        const canvas = await Canvas.findOne({
            _id: req.params.canvasId,
            $or: [
                { owner: req.user.userId },
                { collaborators: req.user.userId }
            ]
        });

        if (!canvas) {
            console.log('画布不存在或用户无权限');
            return res.status(404).json({
                code: 404,
                msg: '画布不存在或您没有权限访问',
                data: null
            });
        }

        console.log('成功获取画布快照');
        res.json({
            code: 200,
            msg: '获取快照成功',
            data: canvas.snapshot
        });
    } catch (error) {
        console.error('获取快照失败:', error);
        res.status(500).json({
            code: 500,
            msg: '获取快照失败',
            data: null,
            error: error.message
        });
    }
});

// 更新画布快照
router.post('/canvas-snapshots/direct/:canvasId', auth, async(req, res) => {
    try {
        console.log('正在更新画布快照:', req.params.canvasId);
        console.log('当前用户ID:', req.user.userId);
        console.log('请求体:', JSON.stringify(req.body).substring(0, 200) + '...');

        // 验证请求体
        if (!req.body || typeof req.body !== 'object') {
            console.log('请求体无效');
            return res.status(400).json({
                code: 400,
                msg: '请求体无效',
                data: null
            });
        }

        const canvas = await Canvas.findOneAndUpdate({
            _id: req.params.canvasId,
            $or: [
                { owner: req.user.userId },
                { collaborators: req.user.userId }
            ]
        }, { snapshot: req.body }, { new: true });

        if (!canvas) {
            console.log('画布不存在或用户无权限');
            return res.status(404).json({
                code: 404,
                msg: '画布不存在或您没有权限更新',
                data: null
            });
        }

        console.log('成功更新画布快照');
        res.json({
            code: 200,
            msg: '更新快照成功',
            data: canvas
        });
    } catch (error) {
        console.error('更新快照失败:', error);
        res.status(500).json({
            code: 500,
            msg: '更新快照失败',
            data: null,
            error: error.message
        });
    }
});

// 调试接口：检查画布快照状态
router.get('/canvas-debug/:canvasId', auth, async(req, res) => {
    try {
        console.log('调试画布:', req.params.canvasId);
        console.log('当前用户ID:', req.user.userId);

        const canvas = await Canvas.findOne({
            _id: req.params.canvasId,
            $or: [
                { owner: req.user.userId },
                { collaborators: req.user.userId }
            ]
        });

        if (!canvas) {
            console.log('画布不存在或用户无权限');
            return res.status(404).json({
                code: 404,
                msg: '画布不存在或您没有权限访问',
                data: null
            });
        }

        // 返回画布的详细信息，包括快照
        const canvasInfo = {
            id: canvas._id,
            title: canvas.title,
            owner: canvas.owner,
            collaborators: canvas.collaborators,
            hasSnapshot: canvas.snapshot !== null,
            snapshotSize: canvas.snapshot ? JSON.stringify(canvas.snapshot).length : 0,
            snapshotPreview: canvas.snapshot ? JSON.stringify(canvas.snapshot).substring(0, 200) + '...' : null,
            createdAt: canvas.createdAt,
            updatedAt: canvas.updatedAt
        };

        console.log('画布调试信息:', canvasInfo);
        res.json({
            code: 200,
            msg: '获取画布调试信息成功',
            data: canvasInfo
        });
    } catch (error) {
        console.error('获取画布调试信息失败:', error);
        res.status(500).json({
            code: 500,
            msg: '获取画布调试信息失败',
            data: null,
            error: error.message
        });
    }
});

// 生成随机分享码的辅助函数
function generateShareCode(length = 6) {
    const bytes = crypto.randomBytes(Math.ceil(length * 3 / 4));
    const code = bytes.toString('base64')
        .replace(/[+/]/g, '') // 移除特殊字符
        .substring(0, length); // 截取指定长度
    return code;
}

// 生成分享码
router.get('/canvas-shares/:canvasId/:expire', auth, async(req, res) => {
    try {
        const { canvasId, expire } = req.params;
        const userId = req.user.userId;

        // 验证画布所有权
        const canvas = await Canvas.findOne({ _id: canvasId, owner: userId });
        if (!canvas) {
            return res.status(404).json({
                success: false,
                msg: '画布不存在或您没有权限'
            });
        }

        // 生成分享码
        const shareCode = generateShareCode();
        const expireAt = new Date(Date.now() + parseInt(expire) * 60 * 1000);

        // 更新画布的分享信息
        canvas.shareCode = {
            code: shareCode,
            expireAt: expireAt
        };
        await canvas.save();

        // 返回分享码
        return res.status(200).json({
            success: true,
            msg: '分享码生成成功',
            data: shareCode
        });
    } catch (error) {
        console.error('生成分享码失败:', error);
        return res.status(500).json({
            success: false,
            msg: '生成分享码失败',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});

// 通过分享码加入协作
router.post('/canvas-shares/:shareCode', auth, async(req, res) => {
    try {
        const { shareCode } = req.params;
        const userId = req.user.userId;

        // 查找具有该分享码的画布
        const canvas = await Canvas.findOne({
            'shareCode.code': shareCode,
            'shareCode.expireAt': { $gt: new Date() }
        });

        if (!canvas) {
            return res.status(404).json({
                success: false,
                msg: '分享码无效或已过期'
            });
        }

        // 检查用户是否已经是协作者
        if (canvas.collaborators.includes(userId)) {
            return res.status(400).json({
                success: false,
                msg: '您已经是该画布的协作者'
            });
        }

        // 添加用户为协作者
        canvas.collaborators.push(userId);
        await canvas.save();

        return res.status(200).json({
            success: true,
            msg: '成功加入协作',
            data: {
                canvasId: canvas._id,
                title: canvas.title
            }
        });
    } catch (error) {
        console.error('加入协作失败:', error);
        return res.status(500).json({
            success: false,
            msg: '加入协作失败',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});

// 退出协作
router.delete('/canvas-collaborate/:canvasId', auth, async(req, res) => {
    try {
        const { canvasId } = req.params;
        const userId = req.user.userId;

        // 验证画布ID格式
        if (!require('mongoose').Types.ObjectId.isValid(canvasId)) {
            return res.status(400).json({
                success: false,
                msg: '无效的画布ID格式'
            });
        }

        const canvas = await Canvas.findOne({
            _id: canvasId,
            collaborators: userId
        });

        if (!canvas) {
            return res.status(404).json({
                success: false,
                msg: '画布不存在或您不是协作者'
            });
        }

        // 从协作者列表中移除用户
        canvas.collaborators = canvas.collaborators.filter(
            collaboratorId => collaboratorId.toString() !== userId.toString()
        );
        await canvas.save();

        res.json({
            success: true,
            msg: '成功退出协作'
        });
    } catch (error) {
        console.error('退出协作失败:', error);
        res.status(500).json({
            success: false,
            msg: '退出协作失败',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});

// 取消分享
router.delete('/canvas-shares/:canvasId', auth, async(req, res) => {
    try {
        const { canvasId } = req.params;
        const userId = req.user.userId;

        // 验证画布所有权
        const canvas = await Canvas.findOne({ _id: canvasId, owner: userId });
        if (!canvas) {
            return res.status(404).json({
                success: false,
                msg: '画布不存在或您没有权限'
            });
        }

        // 清除分享码
        canvas.shareCode = undefined;
        // 移除所有协作者
        canvas.collaborators = [];
        await canvas.save();

        return res.status(200).json({
            success: true,
            msg: '取消分享成功'
        });
    } catch (error) {
        console.error('取消分享失败:', error);
        return res.status(500).json({
            success: false,
            msg: '取消分享失败',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});

// 处理元素操作
router.post('/canvas-operations/:canvasId', auth, async(req, res) => {
    try {
        const { canvasId } = req.params;
        const userId = req.user.userId;
        const operation = req.body;

        // 验证用户是否有权限操作该画布
        const canvas = await Canvas.findOne({
            _id: canvasId,
            $or: [
                { owner: userId },
                { collaborators: userId }
            ]
        });

        if (!canvas) {
            return res.status(404).json({
                success: false,
                msg: '画布不存在或您没有权限'
            });
        }

        // 更新画布快照
        canvas.snapshot = operation;
        await canvas.save();

        return res.status(200).json({
            success: true,
            msg: '操作成功',
            data: canvas.snapshot
        });
    } catch (error) {
        console.error('处理元素操作失败:', error);
        return res.status(500).json({
            success: false,
            msg: '处理元素操作失败',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});

module.exports = router;